package com.smartsofa.main;

import java.io.File;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.smartsofa.R;
import com.smartsofa.entity.InterestTag;
import com.smartsofa.util.MyUtils;

public class LoginActivity extends Activity{
	
	private ImageView user_img;
	private EditText et_username;
	private EditText et_password;
	private Button bt_login;
	private Button bt_register;
	private CheckBox remember;
	private CheckBox autologin;
    private SharedPreferences sp;
	
	private String username;
	private String password;
	
	private String url;
	private Boolean flag=false;
	
	private ProgressDialog mDialog;	
	
	private Intent intent =new Intent();
	
	private JSONObject json;
	
	private Boolean flag_info = false;
	private Boolean flag_image = false;
	
	//定义网络连接超时判定变量
	private boolean network_timeout=false;
	//定义下载用户头像超时判定变量
	private boolean getUserimg_timeout=false;
	
    // 定义一个变量，来标识是否退出
    private static boolean isExit = false;
    //定义登录进程，方便随时结束
    private Thread login_thread;
     
    
    Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            isExit = false;
        }
    };
    
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exit();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void exit() {
        if (!isExit) {
            isExit = true;
            Toast.makeText(getApplicationContext(), "再按一次退出程序",
                    Toast.LENGTH_SHORT).show();
            // 利用handler延迟发送更改状态信息
            mHandler.sendEmptyMessageDelayed(0, 2000);
        } else {
            finish();
            System.exit(0);
        }
    }

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);			
		setContentView(R.layout.login);				
		initView();	
	}
	private void initView(){
		user_img=(ImageView) findViewById(R.id.login_user_img);
		et_username=(EditText) findViewById(R.id.et_username);
		et_password=(EditText) findViewById(R.id.et_password);
		bt_login=(Button)findViewById(R.id.bt_login);
		bt_register=(Button)findViewById(R.id.bt_turn_register);
		
	    remember = (CheckBox) findViewById(R.id.remember);
        autologin = (CheckBox) findViewById(R.id.autologin);

        sp = getSharedPreferences("userInformation", 0);
        String name=sp.getString("username", "");
        String pass =sp.getString("password", "");	
        int userid=sp.getInt("userid", 0);
        String imgurl=sp.getString("imageurl", "");


        boolean choseRemember =sp.getBoolean("remember", false);
        boolean choseAutoLogin =sp.getBoolean("autologin", false);
        
      //如果上次选了记住密码，那进入登录页面也自动勾选记住密码，并填上用户名和密码
        if(choseRemember){
        	et_username.setText(name);
        	et_password.setText(pass);
            remember.setChecked(true);
            
            if(userid>0){
            	/**
        		 * 判断本地是否有缓存的图片
        		 */
        		String imagefileString  = Environment.getExternalStorageDirectory() +"/user_img_"+userid+".png";
        	    File file = new File(imagefileString);
        	    if(file.exists()){
        	    	Bitmap bitmap = BitmapFactory.decodeFile(imagefileString);   	    	
        	    	user_img.setImageBitmap(MyUtils.toRoundCorner(bitmap, 10));
        	    }
            }
            
        }
        //如果上次登录选了自动登录，那进入登录页面也自动勾选自动登录
        if(choseAutoLogin){
            autologin.setChecked(true);
            MyUtils.setUSERID(userid);
          
	    	intent.setClass(LoginActivity.this, MainActivity.class);		
			startActivity(intent);	
			LoginActivity.this.finish();
		    
        }
		
		
		bt_login.setOnClickListener(new OnClickListener() {
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				username=et_username.getText().toString();
				password=et_password.getText().toString();
				
				if(username.equals("")||password.equals("")){
					Toast.makeText(LoginActivity.this,"用户名或密码不能为空！",Toast.LENGTH_SHORT).show();
				}	
				else{
					boolean netstate=MyUtils.isNetworkConnected(getApplicationContext());		
					if(!netstate){
						Toast.makeText(LoginActivity.this,"网络无法连接，请检查你的网络！",Toast.LENGTH_SHORT).show();
					}else{
						login();					
					}					 
				}
			}						
		});
		bt_register.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				intent.setClass(LoginActivity.this, RegisterActivity.class);
				startActivity(intent);
			}
		});
	}
	private void login(){
		
			mDialog = new ProgressDialog(LoginActivity.this);
			mDialog.setTitle("登录");
			mDialog.setMessage("正在登录，请稍候...");
			mDialog.setCancelable(true);
			mDialog.show();
//			mDialog.setOnCancelListener(new DialogCancleEvent());
/*			bt_login.setClickable(false);
			bt_login.setBackgroundColor(getResources().getColor(R.color.light_gray));*/
			//获取登录线程
			login_thread = new Thread(new LoginNet());
			login_thread.start();		
			}
/*	class DialogCancleEvent implements OnCancelListener{

		@SuppressWarnings("deprecation")
		@Override
		public void onCancel(DialogInterface arg0) {
			// TODO Auto-generated method stub
			login_thread.stop();
		}
		
	}*/
	
	private class LoginNet implements Runnable{
			@Override
			public void run() {
				try {	
					url=MyUtils.getUrl()+"user_login?login="+username+"&password="+password;
					Log.i("url", url);
					HttpGet request = new HttpGet(url);																
			       // 发送请求
				   BasicHttpParams httpParams = new BasicHttpParams();
				   HttpConnectionParams.setConnectionTimeout(httpParams,MyUtils.REQUEST_TIMEOUT);
			       HttpClient httpClient = new DefaultHttpClient(httpParams);
			       HttpResponse httpResponse = httpClient.execute(request);					       
			       	
			      if (httpResponse.getStatusLine().getStatusCode() == 200) {
				    	network_timeout=true;
				        String jsonString = EntityUtils.toString(httpResponse.getEntity());
				        json = new JSONObject(jsonString);
				        flag=(Boolean) json.get("success");
				       			       
			      }
			      }catch (Exception e) {
			        	 e.printStackTrace();
			      }
				Message msg = content_handler.obtainMessage();
				if(network_timeout){
					if (flag) {				
						msg.what = 1;									
					}else{
						msg.what = 2;			
					}
				}			
				else{
					msg.what = 3;						
				}
				content_handler.sendMessage(msg);
				}
			}
	Handler content_handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {		
			case 1:
		        try {
					MyUtils.setUSERID(json.getJSONObject("obj").getInt("userId"));	
					//保存用户名和密码
					SharedPreferences.Editor editor =sp.edit();
					editor.putString("username", username);
					editor.putString("password", password); 
					editor.putInt("userid", MyUtils.getUSERID());					
					editor.putString("telenumber", json.getJSONObject("obj").getString("cellphone"));
					editor.putString("deviceid", String.valueOf(json.getJSONObject("obj").getInt("deviceId")));
					if(json.getJSONObject("obj").has("weight")){
						editor.putString("weight", String.valueOf(json.getJSONObject("obj").getDouble("weight")));
					}
					if(json.getJSONObject("obj").has("height")){
						editor.putString("height", String.valueOf(json.getJSONObject("obj").getDouble("height")));
					}
					if(json.getJSONObject("obj").has("interestTag")){
						editor.putString("interestTag", String.valueOf(json.getJSONObject("obj").getString("interestTag")));
					}
					editor.putString("gender", String.valueOf(json.getJSONObject("obj").getInt("sex")));

					if(!json.getJSONObject("obj").optString("birthday").equals("")){
						editor.putString("birthday", json.getJSONObject("obj").optString("birthday").substring(0,10));
					}
					if(!json.getJSONObject("obj").optString("userImg").equals("")){
						editor.putString("imageurl", json.getJSONObject("obj").optString("userImg"));
					}

					//计算用户BMI指数
					float bmi=MyUtils.getBmiIndex(json.getJSONObject("obj").getDouble("height"), json.getJSONObject("obj").getDouble("weight"));
					editor.putFloat("bmi", bmi);
					//判断bmi指数范围：18.5-23.9																		
					if(bmi<18.5){
						InterestTag.interest_list.remove(InterestTag.PANG);
					}else if(bmi>23.9){
						InterestTag.interest_list.remove(InterestTag.SHOU);
					}else{
						InterestTag.interest_list.remove(InterestTag.PANG);
						InterestTag.interest_list.remove(InterestTag.SHOU);
					}							
															
					//是否记住密码
					if(remember.isChecked()){                        
					    editor.putBoolean("remember", true);                        
					}else{
					    editor.putBoolean("remember", false);                
					}               
					                                        
					//是否自动登录
					if(autologin.isChecked()){                            
					    editor.putBoolean("autologin", true);                            
					}else{
					    editor.putBoolean("autologin", false);
					}
					editor.commit();
					
			    	mDialog.dismiss();
			    	intent.setClass(LoginActivity.this, MainActivity.class);		
	    			startActivity(intent);	
	    			LoginActivity.this.finish();
				    
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				break;
			case 2:
/*				bt_login.setClickable(true);
				bt_login.setBackgroundColor(getResources().getColor(R.color.theme));*/
				mDialog.dismiss();
				Toast.makeText(LoginActivity.this, "用户名或密码错误！", Toast.LENGTH_SHORT).show();
				break;
			
			case 3:
/*				bt_login.setClickable(true);
				bt_login.setBackgroundColor(getResources().getColor(R.color.theme));*/
				mDialog.dismiss();
				Toast.makeText(LoginActivity.this, "网络连接超时！", Toast.LENGTH_SHORT).show();
				break;
			}
		}
	};
}
